#include "stdafx.h"
#include "Gray2Bit.h"


Gray2Bit::Gray2Bit()
{
}


Gray2Bit::~Gray2Bit()
{
}

Mat Gray2Bit::DoGray2Bit(Mat image, int threshold, bool isReverse)
{
	Mat I = image;
	Mat r(I.rows, I.cols, CV_8UC1);
	// accept only char type matrices
	CV_Assert(I.depth() == CV_8U);
	int channels = I.channels();

	int nRows = I.rows;
	int nCols = I.cols;

	if (I.isContinuous())
	{
		nCols *= nRows;
		nRows = 1;
	}

	int i, j;
	uchar* p;
	uchar* rp;
	for (i = 0; i < nRows; ++i)
	{
		p = I.ptr<uchar>(i);
		rp = r.ptr<uchar>(i);
		for (j = 0; j < nCols; ++j)
		{
			if (isReverse)
			{
				if (p[3 * j] + p[3 * j + 1] + p[3 * j + 2] < threshold)
					rp[j] = 255;
				else
					rp[j] = 0;
			}
			else
			{
				if (p[3 * j] + p[3 * j + 1] + p[3 * j + 2] < threshold)
					rp[j] = 0;
				else
					rp[j] = 255;
			}
		}
	}
	return r;
}
